<?php

class Admin extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->spark('ion_auth/2.3.2');
        $this->load->spark('grocery-crud/1.3.2');
        $this->load->helper(array('form', 'url'));
    }

    public function index()
    {

        //is the user logged in?
        if (!$this->ion_auth->is_admin()) {
            //redirect them back to the page they came from
            redirect($this->config->item('base_url'), 'refresh');
        }

        $user = $this->ion_auth->user()->row();
        $data = array('title' => 'Kivaou', 'navbar_content' => 'admin/admin_navbar', 'navbar_style' => 'navbar-admin', 'navbar_inverse_style' => 'navbar-inverse', 'navbar_inner_style' => 'navbar-admin-inner', 'main_content' => 'admin/admin_v', 'user_firstname' => $user->first_name, 'user_lastname' => $user->last_name);
        $this->load->view('templates/home', $data);
    }

    public function pupils($errors = FALSE)
    {

        //is the user logged in?
        if (!$this->ion_auth->logged_in()) {
            //redirect them back to the page they came from
            redirect($this->config->item('base_url'), 'refresh');
        }

        $crud = new grocery_CRUD();

        $crud->set_theme('datatables');
        $crud->set_table('pupils');
        $crud->set_relation('class', 'classes', 'name');
        $crud->display_as('name', 'Pr&eacute;nom');
        $crud->display_as('surname', 'Nom');
        $crud->display_as('class', 'Classe');
        $crud->set_subject('El&egrave;ve');
        $crud->unset_jquery();

        $grocery_output = $crud->render();

        $this->load->model('classes_model');
        $classes = $this->classes_model->get_classes();

        foreach ($classes as $classe) $ret[$classe["name"]]=$classe["name"];
        $classes = $ret;

        $user = $this->ion_auth->user()->row();
        if ($errors !== FALSE){
            $data = array('title' => 'Kivaou', 'navbar_content' => 'admin/admin_navbar', 'navbar_style' => 'navbar-admin', 'navbar_inverse_style' => 'navbar-inverse', 'navbar_inner_style' => 'navbar-admin-inner', 'main_content' => 'admin/admin_pupils', 'user_firstname' => $user->first_name, 'user_lastname' => $user->last_name, 'pupils' => $grocery_output, 'classes' => $classes,'error' => $errors);
        }else{
            $data = array('title' => 'Kivaou', 'navbar_content' => 'admin/admin_navbar', 'navbar_style' => 'navbar-admin', 'navbar_inverse_style' => 'navbar-inverse', 'navbar_inner_style' => 'navbar-admin-inner', 'main_content' => 'admin/admin_pupils', 'user_firstname' => $user->first_name, 'user_lastname' => $user->last_name, 'pupils' => $grocery_output, 'classes' => $classes);
        }
            $this->load->view('templates/home', $data);

    }

    public function classes()
    {

        //is the user logged in?
        if (!$this->ion_auth->logged_in()) {
            //redirect them back to the page they came from
            redirect($this->config->item('base_url'), 'refresh');
        }

        $user = $this->ion_auth->user()->row();

        $crud = new grocery_CRUD();

        $crud->set_theme('datatables');
        $crud->set_table('classes');
        $crud->set_relation('level', 'levels', 'name');
        $crud->display_as('name', 'Nom');
        $crud->display_as('level', 'Niveau');
        $crud->set_subject('Classe');
        $crud->unset_jquery();

        $grocery_output = $crud->render();

        $user = $this->ion_auth->user()->row();
        $data = array('title' => 'Kivaou', 'navbar_content' => 'admin/admin_navbar', 'navbar_style' => 'navbar-admin', 'navbar_inverse_style' => 'navbar-inverse', 'navbar_inner_style' => 'navbar-admin-inner', 'main_content' => 'admin/admin_classes', 'user_firstname' => $user->first_name, 'user_lastname' => $user->last_name, 'classes' => $grocery_output);
        $this->load->view('templates/home', $data);

    }

    public function rooms()
    {

        //is the user logged in?
        if (!$this->ion_auth->logged_in()) {
            //redirect them back to the page they came from
            redirect($this->config->item('base_url'), 'refresh');
        }

        $user = $this->ion_auth->user()->row();

        $crud = new grocery_CRUD();

        $crud->set_theme('datatables');
        $crud->set_table('rooms');
        $crud->display_as('name', 'Nom');
        $crud->display_as('capacity', 'Nombre de places');
        $crud->display_as('special', 'Salle sp&eacute;ciale');
        $crud->field_type('special', 'true_false');
        $crud->set_subject('Salle');
        $crud->unset_jquery();


        $grocery_output = $crud->render();

        $user = $this->ion_auth->user()->row();
        $data = array('title' => 'Kivaou', 'navbar_content' => 'admin/admin_navbar', 'navbar_style' => 'navbar-admin', 'navbar_inverse_style' => 'navbar-inverse', 'navbar_inner_style' => 'navbar-admin-inner', 'main_content' => 'admin/admin_rooms', 'user_firstname' => $user->first_name, 'user_lastname' => $user->last_name, 'rooms' => $grocery_output);
        $this->load->view('templates/home', $data);

    }

    public function teachers_timetables()
    {

        //is the user logged in?
        if (!$this->ion_auth->logged_in()) {
            //redirect them back to the page they came from
            redirect($this->config->item('base_url'), 'refresh');
        }

        $user = $this->ion_auth->user()->row();

        $crud = new grocery_CRUD();

        $crud->set_theme('datatables');
        $crud->set_table('teachers_timetables');
        $crud->set_relation('day_number', 'days', 'name', null, 'number ASC');
        $crud->set_relation('room_name', 'rooms', 'name');
        $crud->set_relation('teacher_id', 'users', '{first_name} {last_name}');
        $crud->display_as('teacher_id', 'Enseignant');

        $crud->unset_jquery();

        $crud->set_subject('Emploi du temps');

        $grocery_output = $crud->render();

        $user = $this->ion_auth->user()->row();
        $data = array('title' => 'Kivaou', 'navbar_content' => 'admin/admin_navbar', 'navbar_style' => 'navbar-admin', 'navbar_inverse_style' => 'navbar-inverse', 'navbar_inner_style' => 'navbar-admin-inner', 'main_content' => 'admin/admin_timetables', 'user_firstname' => $user->first_name, 'user_lastname' => $user->last_name, 'timetables' => $grocery_output);
        $this->load->view('templates/home', $data);

    }

    public function users()
    {

        //is the user logged in?
        if (!$this->ion_auth->logged_in()) {
            //redirect them back to the page they came from
            redirect($this->config->item('base_url'), 'refresh');
        }

        $user = $this->ion_auth->user()->row();

        $crud = new grocery_CRUD();

        $crud->set_theme('datatables');
        $crud->set_table('users');

        $crud
            ->columns('first_name', 'last_name', 'email', 'phone', 'company', 'groups', 'active')
            ->fields('first_name', 'last_name', 'email', 'phone', 'company', 'groups', 'active', 'change_password', 'edit_password', 'edit_password_confirm')
            ->display_as('change_password', 'Changer le mot de passe ?')
            ->display_as('first_name', 'Pr&eacute;nom')
            ->display_as('last_name', 'Nom')
            ->display_as('email', 'Email')
            ->display_as('phone', 'T&eacute;l&eacute;phone')
            ->display_as('company', 'Entreprise')
            ->display_as('groups', 'Groupes')
            ->display_as('active', 'Actif')
            ->change_field_type('change_password', 'true_false')
            ->change_field_type('edit_password', 'password')
            ->change_field_type('edit_password_confirm', 'password')
            ->set_rules('change_password', 'Change password', 'callback__change_password_check')
            ->set_rules('edit_password', 'Password', 'min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']')->set_relation_n_n('groups', 'users_groups', 'groups', 'user_id', 'group_id', 'description');


        $crud->callback_insert(array($this, 'create_user_callback'));
        $crud->callback_update(array($this, 'edit_user_callback'));
        $crud->callback_delete(array($this, 'delete_user'));
        $crud->unset_jquery();


        $crud->set_subject('Utilisateurs');

        $grocery_output = $crud->render();

        $user = $this->ion_auth->user()->row();
        $data = array('title' => 'Kivaou', 'navbar_content' => 'admin/admin_navbar', 'navbar_style' => 'navbar-admin', 'navbar_inverse_style' => 'navbar-inverse', 'navbar_inner_style' => 'navbar-admin-inner', 'main_content' => 'admin/admin_users', 'user_firstname' => $user->first_name, 'user_lastname' => $user->last_name, 'users' => $grocery_output);
        $this->load->view('templates/home', $data);

    }

    function delete_user($primary_key)
    {

        if ($this->ion_auth_model->delete_user($primary_key)) {
            return true;
        } else {
            return false;
        }
    }

    function edit_user_callback($post_array, $primary_key = null)
    {

        $username = $post_array['first_name'] . ' ' . $post_array['last_name'];
        $email = $post_array['email'];
        $data = array(
            'username' => $username,
            'email' => $email,
            'phone' => $post_array['phone'],
            'first_name' => $post_array['first_name'],
            'last_name' => $post_array['last_name']
        );

        $this->ion_auth_model->update($primary_key, $data);

        return true;
    }

    function create_user_callback($post_array, $primary_key = null)
    {

        $username = $post_array['first_name'] . ' ' . $post_array['last_name'];
        $password = $post_array['password'];
        $email = $post_array['email'];
        $data = array(
            'phone' => $post_array['phone'],
            'first_name' => $post_array['first_name'],
            'last_name' => $post_array['last_name']
        );

        $this->ion_auth_model->register($username, $password, $email, $data);

        return $this->db->insert_id();
    }

    function do_pupils_upload()
    {
        //is the user logged in?
        if (!$this->ion_auth->logged_in()) {
            //redirect them back to the page they came from
            redirect($this->config->item('base_url'), 'refresh');
        }

        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('classe', 'Classe', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->pupils();
        } else {

            $config['upload_path'] = './uploads/';
            $config['max_size'] = '0';
            $config['allowed_types'] = '*';

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload("pupils")) {
                $error = $this->upload->display_errors();
                $this->pupils($error);
            } else {
                $data = $this->upload->data();
                $classname = $this->input->post('classe');
                if (isset($data["file_name"], $classname)) {
                    $this->insert_uploaded_pupils($data["file_name"], $classname);
                    $this->pupils();
                } else {
                    $error = "file_name not set, cannot compute Dave!";
                    $this->pupils($error);
                }
            }
        }
    }

    private function insert_uploaded_pupils($filename, $classname)
    {
        // Load the spreadsheet reader library
        $this->load->library('excel');
        $this->load->library('ScolinfoPupilsFilter');
        $this->load->library('ScolinfoPupilsClassFilter');
        $this->load->model('pupils_model');
        /** Load $inputFileName to a PHPExcel Object  **/
        try {

            $inputFileName = "./uploads/$filename";
            /**  Identify the type of $inputFileName  **/
            $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
            /**  Create a new Reader of the type that has been identified  **/
            $objReader = PHPExcel_IOFactory::createReader($inputFileType);
            $filterSubset = new ScolinfoPupilsFilter();
            $objReader->setReadFilter($filterSubset);
            $objPHPExcel = $objReader->load($inputFileName);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            foreach ($objWorksheet->getRowIterator() as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(true); // This loops all cells,
                foreach ($cellIterator as $cell) {
                    switch ($cell->getColumn()) {
                        case "D":
                            $name = $cell->getValue();
                            break;
                        case "I":
                            $surname = $cell->getValue();
                            break;
                    }
                }

                if (isset($name, $surname, $classname)) {
                    $data = array(
                        'name' => $name,
                        'surname' => $surname,
                        'class' => $classname
                    );
                    $this->pupils_model->add_pupil($data);
                }
            }
        } catch (Exception $e) {
            die('Error loading file: ' . $e->getMessage());
        }
    }
}
